package com.smalls.newvideotwo.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.smalls.newvideotwo.R;
import com.smalls.newvideotwo.mvp.bean.MovieDetail;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.TimeZone;

/**
 * Created by 林鸿博 on 2017/1/20.
 */

public class MyUtils {

    /**
     * 获取SDK版本
     */
    public static int getSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
        }
        return version;
    }

    public static String getAppVersion(Context context){
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int getTimeZone(){
        TimeZone timeZone = TimeZone.getDefault();
        int ret = timeZone.getRawOffset() / 3600000;
        return ret;
    }

    private static ActivityManager.MemoryInfo getMemoryInfo(Context context){
        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        if(activityManager != null){
            activityManager.getMemoryInfo(memoryInfo);
        }
        return memoryInfo;
    }

    public static long getTotalMemory(Context context){
        ActivityManager.MemoryInfo memoryInfo = getMemoryInfo(context);
        return memoryInfo.totalMem;
    }

    public static long getUsedMemory(Context context){
        return getTotalMemory(context) - getAvailMemory(context);
    }

    public static long getAvailMemory(Context context){
        ActivityManager.MemoryInfo memoryInfo = getMemoryInfo(context);
        return memoryInfo.availMem;
    }





    public static int getMB(long size){
        float ret = 0.0f;
        ret = size / (float)1024;
        ret = ret / (float)1024;
        return (int)ret;
    }

    private static long mBaseUserTime = 0;
    private static long mBaseSystemTime = 0;
    private static long mBaseIoWaitTime = 0;
    private static long mBaseIrqTime = 0;
    private static long mBaseSoftIrqTime = 0;
    private static long mBaseIdleTime = 0;

    private static boolean readStat(long[] sysCPU){
        boolean ret = false;
        try {
            FileReader fileReader = new FileReader("/proc/stat");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String string = bufferedReader.readLine();
            String tmp[] = string.split(" ");
            if(sysCPU != null){
                for(int i = 2; i < tmp.length && i - 2 < sysCPU.length; ++i){
                    sysCPU[i - 2] = Long.parseLong(tmp[i]);
                }
            }

            ret = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;

    }

    public static int getUsedCPU(){
        int ret = 0;
        long[] sysCpu = new long[7];
        if (readStat(sysCpu)) {
            // Total user time is user + nice time.
            long usertime = sysCpu[0]+sysCpu[1];
            // Total system time is simply system time.
            long systemtime = sysCpu[2];
            // Total idle time is simply idle time.
            long idletime = sysCpu[3];
            // Total irq time is iowait + irq + softirq time.
            long iowaittime = sysCpu[4];
            long irqtime = sysCpu[5];
            long softirqtime = sysCpu[6];

            long relUserTime = (int)(usertime - mBaseUserTime);
            long relSystemTime = (int)(systemtime - mBaseSystemTime);
            long relIoWaitTime = (int)(iowaittime - mBaseIoWaitTime);
            long relIrqTime = (int)(irqtime - mBaseIrqTime);
            long relSoftIrqTime = (int)(softirqtime - mBaseSoftIrqTime);
            long relIdleTime = (int)(idletime - mBaseIdleTime);

            long totalTime = relUserTime + relSystemTime + relIoWaitTime + relIrqTime + relSoftIrqTime + relIdleTime;
            ret = (int) (100 * (totalTime - relIdleTime) / totalTime);

            mBaseUserTime = usertime;
            mBaseSystemTime = systemtime;
            mBaseIoWaitTime = iowaittime;
            mBaseIrqTime = irqtime;
            mBaseSoftIrqTime = softirqtime;
            mBaseIdleTime = idletime;
        }
        return ret;
    }

    /**
     * Toast
     */
    public static void toast(Context context, String message) {
        Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
        toast.show();
    }

    /**
     * 设置 imageView 是否变灰
     *
     * @param imageView imageView
     * @param gray      是否变灰
     */
    public static void setImageViewGray(ImageView imageView, boolean gray) {
        if (gray) {
            int color = imageView.getContext().getResources().getColor(R.color.black2);
            imageView.setColorFilter(color);
        } else {
            imageView.clearColorFilter();
        }
    }

    /**
     * 根据时长获取字符串
     *
     * @param duration 时长
     * @return xx:xx:xx 字符串
     */
    public static String getDuration(long duration) {
        if (duration <= 0){
            return "00:00:00";
        }
        String format = "%1$02d:%2$02d:%3$02d";
        String ret = String.format(format,
                duration / 3600,
                (duration % 3600) / 60,
                duration % 60);
        return ret;
    }

    /**
     * 设置 view 可视
     *
     * @param view       view
     * @param visibility 可视参数
     */
    public static void setVisibility(View view, int visibility) {
        if (view != null && view.getVisibility() != visibility) {
            view.setVisibility(visibility);
        }
    }

    /**
     * 设置 text
     *
     * @param textView textView
     * @param text     设置的字符串
     * @return 字符串是否为 null
     */
    public static boolean setText(TextView textView, String text) {
        boolean ret = true;
        if (textView != null) {
            if (TextUtils.isEmpty(text) || "null".equalsIgnoreCase(text)) {
                text = "";
                ret = false;
            }
            if (text.startsWith(",")) {
                text = text.substring(1);
            }
            if (text.endsWith(",")) {
                text = text.substring(0, text.length() - 1);
            }
            if (TextUtils.isEmpty(text) || "null".equalsIgnoreCase(text)) {
                text = "";
                ret = false;
            }
            textView.setText(text);
        }
        return ret;
    }


    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFiles(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    //public static MediaDetailItem createMediaDetail(JSONObject jsonObject){
    //    return MediaDetailItem.createItem(jsonObject);
    //}
}
